var num=5;
function snakeMatrix(num) {
    var row = num,col = row;
    var q = Math.ceil(num / 2);
    var result = new Array(row);
    for(var i=0;i<row;i++){
        result[i] = new Array(col);
    }
    var n = 0;
    var begin = 1;
    while(n <= q){
        var top = col - 2 * n;
        for (var i = 0; i < top; i++) {
            result[n][i+n] = begin + i;
        }
        var right = row - 2 * n;
        for (var i = 0; i < right; i++) {
            result[i+n][col-n-1] = begin + top + i -1;
        }
        var bottom = col - 2 * n;
        for (var i = 0; i < bottom; i++) {
            result[row-n-1][col-n-i-1] = begin + top + right + i - 2;
        }
        var left = row - 2 * n - 1;
        for (var i = 0; i < left; i++) {
            result[row-i-n-1][n] = begin + top + right + bottom + i - 3;
        }
        begin += top + right + bottom + left - 3;
        n++;
    }
    return result;
}
console.log(snakeMatrix(5));